package ru.pb.auth.network.clients;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import ru.pb.auth.controllers.AuthController;
import ru.pb.auth.data.xml.holders.GameServersHolder;
import ru.pb.auth.model.GameServerInfo;
import ru.pb.auth.network.engine.game.packets.sendable.INIT;
import ru.pb.global.network.MacAddr;
import ru.pb.global.network.engine.NioClient;
import ru.pb.global.network.engine.NioService;
import ru.pb.global.network.engine.NioSession;
import ru.pb.global.network.engine.core.interfaces.IPacketExecutor;

/**
 * Клиент гейм сервера
 * 
 * @author Felixx
 */
public class GameServerClient extends NioClient<GameServerClient>
{
	private final Map<String, Integer> _accountsInGameServer = new ConcurrentHashMap<String, Integer>();
	private GameServerInfo _gameServerInfo;
	private int _online = 0;

	public GameServerClient(NioSession<GameServerClient> session, NioService service, IPacketExecutor executor)
	{
		super(session, service, executor);
	}

	@Override
	public void onStart()
	{
		sendPacket(new INIT());
	}

	@Override
	public void onEnd()
	{
		disconnect();
	}

	@Override
	public void onForceEnd()
	{
		disconnect();
	}

	@Override
	public void catchException(Throwable cases)
	{
		_log.info("Exception: " + cases);
	}

	public void disconnect()
	{
		if(_gameServerInfo != null)
		{
			_gameServerInfo.setDown();
			if(_gameServerInfo.isTemp())
				GameServersHolder.getInstance().remove(_gameServerInfo);
		}
	}

	public void clearAccountInGameServer()
	{
		_accountsInGameServer.clear();
	}

	public void addAccountInGameServer(String account)
	{
		if(_accountsInGameServer.containsKey(account))
			return;

		_accountsInGameServer.put(account, 0);
	}

	public void removeAccountFromGameServer(String account)
	{
		_accountsInGameServer.remove(account);
	}

	public boolean isAccountInGameServer(String account)
	{
		return _accountsInGameServer.containsKey(account);
	}

	public int getPlayerCount()
	{
		return _online;
	}

	public void setPlayerCount(int i)
	{
		_online = i;
	}

	public GameServerInfo getGameServerInfo()
	{
		return _gameServerInfo;
	}

	public void setGameServerInfo(GameServerInfo gameServerInfo)
	{
		_gameServerInfo = gameServerInfo;
	}

	public void kickByAccount(String account, boolean kick)
	{
		// TODO кики акаунта sendPacket(new KickPlayer(account, kick));
		if(kick)
		{
			removeAccountFromGameServer(account);
			AuthController.getInstance().removeAuthedLoginClient(account);
		}
	}

	@Override
	public MacAddr getMac()
	{
		return null;
	}

	@Override
	public void setMAC(MacAddr mac)
	{}
}